package util;

import org.springframework.beans.factory.annotation.Value;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 模拟redis缓存，存放登录信息
 */
public class MockRedis {

    @Value("${REDIS_PERIOD}")
    private long REDIS_PERIOD;

    private ConcurrentHashMap<String, ExpireValue> map = new ConcurrentHashMap<>();
    private volatile boolean isShutdown = false;


    public MockRedis() {
        new Thread(new ClearTask()).start();
    }


    public void set(String key, String value) {

        map.put(key, new ExpireValue(value));

    }

    public String get(String key) {

        ExpireValue expireValue = map.get(key);
        if (expireValue == null) {
            return null;
        }
        long now = System.currentTimeMillis();
        if (now - expireValue.setTime > expireValue.expire) {
            map.remove(key);
            return null;
        }
        return expireValue.value;
    }

    public boolean expire(String key, long expire) {
        ExpireValue expireValue = map.get(key);
        if (expireValue == null) {
            return false;
        }
        expireValue.setTime=System.currentTimeMillis();
        expireValue.setExpire(expire);
        return true;
    }

    public void disconnect() {
        isShutdown = true;
    }


    class ExpireValue {
        String value;
        //单位毫秒
        long setTime;
        //单位秒
        long expire;

        public ExpireValue(String value, long setTime, long expire) {
            this.value = value;
            this.expire = expire;
            this.setTime = setTime;
        }

        public ExpireValue(String value) {
            this.value = value;
            this.expire = 0;
            this.setTime = System.currentTimeMillis();
        }

        public void setExpire(long expire) {
            this.expire = expire * 1000;  //转化成毫秒
        }

    }


    class ClearTask implements Runnable {

        @Override
        public void run() {
            while (!isShutdown) {
                for (Map.Entry<String, ExpireValue> entry : map.entrySet()) {
                    ExpireValue expireValue = entry.getValue();
                    long now = System.currentTimeMillis();
                    if (now - expireValue.setTime > expireValue.expire) {
                        map.remove(entry.getKey());
                        //TODO  debug
                        System.out.println("清理周期：  " + entry.getKey());
                    }
                }

                try {
                    Thread.sleep(REDIS_PERIOD);
                } catch (InterruptedException e) {
                    isShutdown = true;
                    //TODO
                    e.printStackTrace();
                }
            }
        }
    }
}
